import Konva from 'konva'
import { useEffect, useRef, useState } from 'react'
import { Group, Layer, Line, Rect, Stage } from 'react-konva'

export default function View() {
  const [tool, setTool] = useState('pen')
  const [lines, setLines] = useState([])
  const isDrawing = useRef(false)
  const groupRef = useRef<Konva.Group>(null)

  // 定义绘制区域的边界
  const editArea = {
    x: 500,
    y: 200,
    width: 512,
    height: 512
  }

  // 定义中心区域的边界（宽度和高度的2倍）
  const centerArea = {
    x: editArea.x - editArea.width / 2, // 左边界
    y: editArea.y - editArea.height / 2, // 上边界
    width: editArea.width * 2, // 中心区域宽度
    height: editArea.height * 2 // 中心区域高度
  }

  const handleMouseDown = e => {
    const stage = e.target.getStage()
    const pos = stage.getPointerPosition()

    // 检查是否在中心区域内
    if (
      pos.x >= centerArea.x &&
      pos.x <= centerArea.x + centerArea.width &&
      pos.y >= centerArea.y &&
      pos.y <= centerArea.y + centerArea.height
    ) {
      isDrawing.current = true
      setLines([...lines, { tool, points: [pos.x, pos.y] }])
    }
  }

  const handleMouseMove = e => {
    if (!isDrawing.current) {
      return
    }

    const stage = e.target.getStage()
    const point = stage.getPointerPosition()

    // 限制鼠标位置到中心区域边界内
    const clampedX = Math.max(centerArea.x, Math.min(point.x, centerArea.x + centerArea.width))
    const clampedY = Math.max(centerArea.y, Math.min(point.y, centerArea.y + centerArea.height))

    // 检查是否在中心区域内
    if (
      clampedX >= centerArea.x &&
      clampedX <= centerArea.x + centerArea.width &&
      clampedY >= centerArea.y &&
      clampedY <= centerArea.y + centerArea.height
    ) {
      const lastLine = lines[lines.length - 1]
      lastLine.points = lastLine.points.concat([clampedX, clampedY])
      lines.splice(lines.length - 1, 1, lastLine)
      setLines(lines.concat())
    } else {
      // 如果鼠标移出中心区域，停止绘图
      isDrawing.current = false
    }
  }

  const handleMouseUp = () => {
    isDrawing.current = false
  }

  useEffect(() => {
    groupRef.current.cache()
  }, [lines])

  return (
    <div>
      <select
        value={tool}
        onChange={e => {
          setTool(e.target.value)
        }}
      >
        <option value='pen'>Pen</option>
        <option value='eraser'>Eraser</option>
      </select>
      <Stage
        width={window.innerWidth}
        height={window.innerHeight}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
      >
        <Layer>
          {/* 绘制区域 */}
          <Rect
            id='editArea'
            x={editArea.x}
            y={editArea.y}
            width={editArea.width}
            height={editArea.height}
            fill='black'
            opacity={0.1}
            listening={true}
          />
          {/* 中心区域 */}
          <Rect
            x={centerArea.x}
            y={centerArea.y}
            width={centerArea.width}
            height={centerArea.height}
            fill='blue'
            opacity={0.2}
            listening={false}
          />
          <Group ref={groupRef}>
            {lines.map((line, i) => (
              <Line
                key={i}
                points={line.points}
                stroke='#df4b26'
                strokeWidth={5}
                tension={0.5}
                lineCap='round'
                lineJoin='round'
                globalCompositeOperation={line.tool === 'eraser' ? 'destination-out' : 'source-over'}
              />
            ))}
          </Group>
        </Layer>
      </Stage>
    </div>
  )
}
